import { Button, Space, message, Select, TreeSelect, Divider,Modal } from 'antd';
import { PlusOutlined, PaperClipOutlined ,ExclamationCircleOutlined} from '@ant-design/icons';
import React, { useState, useRef, useEffect } from 'react';
const { confirm } = Modal;
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { queryUser, updateUser, addUser, removeUser,updatePassword,batchRemoveUser } from '@/services/user';
import { queryDepartTree } from '@/services/department';
import { roleList } from '@/services/role';
import styles from '@/global.less';
import { paramToStringRemovePage } from '@/utils/utils'

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    await addUser(fields);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateUser(fields);
    hide();

    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};


/**
 * 更新节点
 * @param fields
 */
 const toResetPassword = async (fields: any) => {
  const hide = message.loading('正在重置密码');
  try {
    await updatePassword(fields);
    hide();

    message.success('密码成功重置为 111111');
    return true;
  } catch (error) {
    hide();
    message.error('重置密码失败请重试！');
    return false;
  }
};




//删除单个
const remove = async (fields: any) => {
  const hide = message.loading('正在删除');
  try {
    await removeUser({userId:fields.userId});
    hide();
    message.success('删除成功，正在刷新！');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};

const { Option } = Select;

const Personnel: React.FC = () => {

  const [roleValues, setRoleValues] = useState<API.RoleItem[]>([]);
  const [departmentTreeData, setDepartmentTreeData] = useState<API.TreeNodeItem[]>([]);
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const actionRef = useRef<ActionType>();
  const [searchDate, setSearchDate] = useState({});


  const columns: ProColumns[] = [
    {
      title: '用户名',
      dataIndex: 'userName',
    },
    {
      title: '姓名',
      dataIndex: 'realName',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      valueEnum: {
        0: { text: '女' },
        1: { text: '男' },
      }
    },
    {
      title: '角色',
      dataIndex: 'roleName',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return (
          <Select placeholder="请选择">
            {(roleValues != undefined?
              roleValues.map((item) => (
                <Option key={item.roleId} value={item.roleId??''}>
                  {item.roleName}
                </Option>
              ))
              :
              null
            )}
          </Select>
        )
      }
    },
    {
      title: '部门',
      dataIndex: 'departmentName',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        return (
          <TreeSelect
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={departmentTreeData}
            placeholder="请选择部门"
            treeDefaultExpandAll
          />
        )
      },

    }, 
    {
      title: '职务',
      dataIndex: 'post',
    },
    {
      title: '职称',
      dataIndex: 'title',
    },
    {
      title: '电话',
      dataIndex: 'phoneNumber',
    }, {
      title: '入职时间',
      dataIndex: 'entryTime',
      search:false,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => (
        <>
        <a
          key="editable"
          onClick={async () => {
            handleUpdateModalVisible(true);
            setFormValues(record);
          }}
        >
          编辑
        </a>
        <Divider type="vertical" />
        <a
          key="editable"
          onClick={async () => {
             toResetPassword({userId:record.userId})
          }}
        >
          重置密码
        </a>
      <Divider type="vertical" />
      <a onClick={() => {
        confirm({
          title: '您确定要删除吗?',
          icon: <ExclamationCircleOutlined />,
          async onOk() {
            await remove(record);
            actionRef.current?.reload();
          },
          onCancel() {
            console.log('Cancel');
          },
        });
      }}
      >
        删除
      </a>
    </>
     )
    },
  ];

  useEffect(() => {
    const setSelectData = async () => {
      const rolelist = await roleList();
      setRoleValues(rolelist);
      let trees = await queryDepartTree();
      setDepartmentTreeData(trees);
    };
    setSelectData();
  }, []);

  const [selectedRowKeys,setSelectedRowKeys] = useState<number[]>([]);
  const onSelectChange = async (sKeys ) => {
    setSelectedRowKeys(sKeys);

  };
  
  //批量删除
  const batchRemove = async () => {
    const hide = message.loading('正在删除');
    try {
      await batchRemoveUser({ ids: selectedRowKeys.join(',')});
      setSelectedRowKeys([]);
      hide();
      message.success('删除成功，正在刷新！');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };

  const ToExport = async () => {
    const hide = message.loading('导出中');
    try {
      window.location.href="/api/exportUserExcel?"+paramToStringRemovePage(searchDate);
      return true;
    } catch (error) {
      hide();
      message.error('导出失败请重试！');
      return false;
    }
  };

  return (
    <>
      <ProTable
        headerTitle=""
        rowKey="userId"
        actionRef={actionRef}
   
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary"   className={styles.addBtn} onClick={() => handleModalVisible(true)}>
            新增
          </Button>,
          <Button icon={<PaperClipOutlined />} type="primary"  className={styles.exportBtn}   onClick={()=>ToExport()}    >
            导出
          </Button>
        ]}
        options={false}
        //request={(params) => queryUser(params)}
        request={(params) =>{setSearchDate(params); return  queryUser(params)} }
        columns={columns}
        rowSelection={{selectedRowKeys,onChange: onSelectChange}}
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={() => {
          return (
            <Space size={16}>
              <a  onClick={() => {
              confirm({
                title: '您确定要批量删除吗?',
                icon: <ExclamationCircleOutlined />,
                async onOk() {
                  await batchRemove();
                  actionRef.current?.reload();
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }} >批量删除</a>
           
            </Space>
          );
        }}
        pagination={{
          defaultCurrent: 1,
          defaultPageSize: 10,
        }}
      />
      <CreateForm
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        rolelist={roleValues}
        departmentlist={departmentTreeData}
      />
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
          rolelist={roleValues}
          departmentlist={departmentTreeData}
        />
      ) : null}
    </>
  );
};

export default Personnel;